package com.ssn.controller.admin;


import com.ssn.po.Type;
import com.ssn.service.ITypeService;
import com.ssn.service.impl.TypeServiceImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.validation.Valid;

@Controller
@RequestMapping("/admin")
public class TypeController {

    @Resource
    private ITypeService typeService;

    @GetMapping("/types")
    public String typePage(@PageableDefault(size = 5,direction = Sort.Direction.DESC) Pageable pageable,
                           Model model){
        model.addAttribute("page", typeService.listType(pageable));
        return "/admin/types";
    }
    @GetMapping("/types/add")
    public String addPage(Model model){
        model.addAttribute("type",new Type());
        return "/admin/input-type";
    }
    @GetMapping("/types/{id}/input")
    public String editPage(@PathVariable Long id,Model model){
        Type type = typeService.getType(id);
        model.addAttribute("type",type);
        return "/admin/input-type";
    }


    @PostMapping("/types/add")
    public String addType(@Valid Type type,
                          BindingResult bindingResult,
                          RedirectAttributes attributes){
        if (bindingResult.hasErrors()){
             return "admin/input-type";
        }
        Type t = typeService.findTypeByName(type.getName());
        if (t != null){
            bindingResult.rejectValue("name","nameError","该分类已经存在，请勿重复添加！");
            return "/admin/input-type";
        }
        typeService.saveType(type);
        attributes.addFlashAttribute("success",true);
        attributes.addFlashAttribute("message","新增类型成功！");
        return "redirect:/admin/types";
    }

    @PostMapping("/types/edit")
    public String editType(@Valid Type type,
                          BindingResult bindingResult,
                          RedirectAttributes attributes){
        if (bindingResult.hasErrors()){
            return "admin/input-type";
        }
        Type t = typeService.findTypeByName(type.getName());
        if (t != null){
            bindingResult.rejectValue("name","nameError","该分类已经存在，请勿重复添加！");
            return "/admin/input-type";
        }
        typeService.updateType(type.getId(),type);
        attributes.addFlashAttribute("success",true);
        attributes.addFlashAttribute("message","修改类型成功！");
        return "redirect:/admin/types";
    }

    @GetMapping("/types/{id}/delete")
    public String deleteType(@PathVariable Long id){
        typeService.deteleType(id);
        return "redirect:/admin/types";
    }

}
